from typing import Any
from modbus_client import ModbusReader
from config_loader import PlcConfig
from utils.logger import get_logger

# 尝试导入FINS客户端（如果存在）
try:
    from fins_client import FINSReader
    FINS_AVAILABLE = True
except ImportError:
    FINS_AVAILABLE = False
    FINSReader = None

logger = get_logger("plc_factory.py+PLCFactory")

class PLCFactory:
    """PLC客户端工厂类"""
    
    @staticmethod
    def create_client(protocol: str, config: PlcConfig) -> Any:
        """
        根据协议类型创建PLC客户端
        
        Args:
            protocol: 协议类型 ('modbus' 或 'fins')
            config: PLC配置
            
        Returns:
            对应协议的客户端实例
        """
        protocol = protocol.lower()
        
        if protocol == 'modbus':
            logger.info("Creating Modbus client")
            return ModbusReader(config)
        elif protocol == 'fins':
            if FINS_AVAILABLE and FINSReader:
                logger.info("Creating FINS client")
                return FINSReader(config)
            else:
                logger.error("FINS protocol not available - FINS client not implemented")
                raise NotImplementedError("FINS protocol not available - FINS client not implemented")
        else:
            logger.error(f"Unsupported protocol: {protocol}")
            raise ValueError(f"Unsupported protocol: {protocol}")